<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="850px"
    append-to-body
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" :show-message="false" label-width="110px" class="mx-10">
      <div class="commonTitle fz-15 fw-6 mb-15">项目基本信息</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="itemName" required>
            <el-input
              :disabled="formDisabled"
              v-model="form.itemName"
              @blur="getPinyinFirstLetter(form.itemName)"
              placeholder="请输入项目名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目首字母" prop="itemPinyin">
            <el-input
              v-model="form.itemPinyin"
              @input="_itemPinyinChange"
              placeholder="输入项目名称即可生成"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编码" prop="itemCode">
            <el-input
              v-model="form.itemCode"
              @input="_itemCodeChange"
              :disabled="formDisabled"
              placeholder="请输入项目编码"
              :maxlength="20"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务归属" prop="serviceItems" required>
            <el-select
              v-model="form.serviceItems"
              placeholder="请先选择服务归属"
              clearable
              :disabled="formDisabled"
              @change="serviceItemsChange"
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.service_items"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目类别" prop="dictCode" required>
            <el-cascader
              style="width: 100%"
              :options="classList"
              placeholder="请选择项目类别"
              :props="{
                label: 'categoryName',
                value: 'categoryId',
                children: 'childList',
                emitPath: false,
              }"
              v-model="form.dictCode"
              :disabled="!form.serviceItems || formDisabled"
              filterable
              @change="classChange"
              ref="ClassCascader"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目售价" prop="checkPrice" required>
            <el-input-number
              :controls="false"
              :precision="4"
              :min="0"
              v-model="form.checkPrice"
              placeholder="请输入项目售价"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目采购价" prop="purchasePrice" required>
            <el-input-number
              :controls="false"
              :precision="4"
              :min="0"
              v-model="form.purchasePrice"
              placeholder="请输入项目采购价"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计量单位" prop="unitId" required>
            <el-select
              v-model="form.unitId"
              placeholder="请选择计量单位"
              clearable
              :disabled="formDisabled"
              style="width: 100%"
            >
              <el-option
                v-for="item in unitList"
                :key="item.unitId"
                :label="item.unit"
                :value="item.unitId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <template v-if="form.dictCode === 7 || form.dictCode === 8">
        <div class="commonTitle fz-15 fw-6 mb-15">中药信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="平台药品编码" prop="platformCode">
              <SelectDrug
                :defaultValue.sync="form.platformCode"
                valueKey="code"
                :status="1"
                ref="SelectDrug"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当量转换比例" prop="convertRatio">
              <el-input-number v-model="form.convertRatio" placeholder="请输入饮片/颗粒的转换比例" :precision="2" :min="1" :controls="false" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <div class="commonTitle fz-15 fw-6 mb-15">其他信息</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目规格" prop="itemSpecs">
            <el-input
              v-model="form.itemSpecs"
              placeholder="请输入项目规格"
              :maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="produceFactory">
            <el-input
              v-model="form.produceFactory"
              placeholder="请输入生产厂家"
              :maxlength="40"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="matterAttent">
            <el-input
              v-model="form.matterAttent"
              placeholder="备注"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import pinyin from "js-pinyin";
import { isString } from "@/utils/is.js";
import SelectDrug from "@/views/saas/drug/selectDrug";

import { checkOrderRelevance, getCategoryList, categoryTree, addInspection, updateInspection, } from "@/api/service";
import { getSelectList } from "@/api/system/unit";

export default {
  dicts: ["service_items"],
  components: {
    SelectDrug
  },
  data() {
    return {
      title: "",
      open: false,
      form: {},
      formDisabled: false,
      classList: [],
      unitList: [], // 计量单位列表
    }
  },
  methods: {
    async openModal(row) {
      this.reset();
      this.formDisabled = false;
      await this.getUnList();
      if (row) {
        for (const key in this.form) {
          this.form[key] = row[key];
        }
        this.serviceItemsChange();
        this.checkRelevance(row.itemId);
        const selectUnit = this.unitList.find(
          (v) => v.unitId === this.form.unitId
        );
        this.form.unitId = selectUnit?.unitId ?? null;
      }
      this.title = row ? "编辑服务项目" : "新增服务项目";
      this.open = true;
      this.$nextTick(() => {
        if(this.$refs.SelectDrug){
          this.$refs.SelectDrug.remoteMethod('');
        }
      });
    },
    _itemPinyinChange(e) {
      this.form.itemPinyin = e.replace(/[^A-Z]/g, "");
    },
    _itemCodeChange(e) {
      this.form.itemCode = e.replace(/[\u4e00-\u9fa5]/g, "");
    },
    getPinyinFirstLetter(str) {
      this.form.itemPinyin =
        !str || !isString(str) ? "" : pinyin.getCamelChars(str);
    },
    // 查询项目类别列表
    async serviceItemsChange(e) {
      if (e || !this.form.serviceItems) {
        this.form.dictCode = "";
        this.form.dictLabel = "";
        if (!this.form.serviceItems) return
      }

      const { data } = await categoryTree({ serviceItems: this.form.serviceItems });
      if (data.length) {
        this.classList = data;
        return
      }

      const { rows } = await getCategoryList({
        serviceItems: this.form.serviceItems,
        pageSize: 9999,
      });
      this.classList = rows.map(v => {
        return {
          categoryId: v.dictCode,
          categoryName: v.dictLabel
        }
      });
    },
    // 获取计量单位
    async getUnList() {
      const { rows } = await getSelectList({ pageNum: 1, pageSize: 999 }); // 获取计量单位
      this.unitList = rows;
    },
    // 检查项目是否关联订单
    checkRelevance(itemId) {
      checkOrderRelevance({ itemId }).then((res) => {
        this.formDisabled = res.isOrder;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: undefined, // 项目ID
        itemName: "", // 项目名称
        itemPinyin: "", // 项目首字母
        itemCode: "", // 项目编码
        platformCode: "", // 平台药品编码
        convertRatio: undefined, // 当量转换比例
        checkPrice: undefined, // 项目售价
        purchasePrice: undefined, // 项目采购价
        unitId: "", // 销售单位
        matterAttent: "", // 注意事项
        serviceItems: "", // 服务归属
        dictLabel: "", // 项目类别label
        dictCode: "", //  项目类别code
        itemSpecs: "", // 项目规格
        produceFactory: "", // 生产厂家
      };
    },
    classChange(v) {
      const nodes = this.$refs.ClassCascader.getCheckedNodes(true);
      this.form.dictLabel = nodes[nodes.length - 1].label || "";
    },
    // 确认新增编辑
    submitForm() {
      const _form = this.form;
      console.log(JSON.parse(JSON.stringify(_form)));
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let params = {
            dictCode: _form.dictCode,
            dictLabel: _form.dictLabel,
            serviceItems: _form.serviceItems,
            checkItem: [
              {
                itemName: _form.itemName,
                itemPinyin: _form.itemPinyin,
                itemCode: _form.itemCode,
                checkPrice: _form.checkPrice,
                unitId: _form.unitId,
                matterAttent: _form.matterAttent,
                platformCode: _form.dictCode === 7 || _form.dictCode === 8 ? _form.platformCode : undefined, // 平台药品编码
                purchasePrice: _form.purchasePrice, // 项目采购价
                itemSpecs: _form.itemSpecs, // 项目规格
                produceFactory: _form.produceFactory, // 生产厂家
                convertRatio: _form.dictCode === 7 || _form.dictCode === 8 ? _form.convertRatio : undefined, // 当量转换比例
              },
            ],
          };
          if (_form.itemId) {
            params.checkItem[0].itemId = _form.itemId;
            await updateInspection(params);
            this.$message.success("修改成功");
          } else {
            await addInspection(params);
            this.$message.success("新增成功");
          }
          this.$emit('refresh');
          this.open = false;
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
</style>
